<?php
/**
*
* @package ppkBB3cker
* @copyright (c) PPK
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
*
*/

/**
* @ignore
*/
if (!defined('IN_PHPBB'))
{
	exit;
}

/**
* @package ppkBB3cker
*/
class portal_ppkbb3cker_ltorrents_module
{
	/**
	* Allowed columns: Just sum up your options (Exp: left + right = 10)
	* top		1
	* left		2
	* center	4
	* right		8
	* bottom	16
	*/
	public $columns = 21;

	/**
	* Default modulename
	*/
	public $name = 'PPKBB3CKER_LTORRENTS';

	/**
	* Default module-image:
	* file must be in "{T_THEME_PATH}/images/portal/"
	*/
	public $image_src = 'portal_menu.png';

	/**
	* module-language file
	* file must be in "language/{$user->lang}/mods/portal/"
	*/
	public $language = 'portal_ppkbb3cker_ltorrents_module';

	/**
	* hide module name in ACP configuration page
	*/
	public $hide_name = false;

	/**
	* custom acp template
	* file must be in "adm/style/portal/"
	*/
	public $custom_acp_tpl = '';

	public function get_template_center($module_id)
	{
		global $phpbb_root_path, $template, $phpEx, $config, $db, $user, $auth, $cache;

		$show_module = true;

		$disallow_access = array_unique(array_keys($auth->acl_getf('!f_read', true)));

		$sql = 'SELECT forum_id, forum_name, forum_image FROM ' . FORUMS_TABLE . ' WHERE forum_type = ' . FORUM_POST . " AND forumas='1'".(sizeof($disallow_access) ? " AND forum_id NOT IN('".implode("', '", $disallow_access)."')" : '');

		$result = $db->sql_query($sql);

		$forum_sql=$update_count=$exclude_forums=array();
		while($row = $db->sql_fetchrow($result))
		{
			$forum_sql[$row['forum_id']]=$row;
		}
		$db->sql_freeresult($result);
		$from_forums=implode("', '", array_keys($forum_sql));

		$start = request_var('tp', 0);
		$start < 0 ? $start=0 : '';
		$ppkbb_portal_last_torrents=my_split_config($config['board3_ppkbb3cker_portal_last_torrents_'.$module_id], 5, 'my_int_val');
		$ppkbb_portal_torrents_posttime=my_split_config($config['board3_ppkbb3cker_portal_torrents_posttime_'.$module_id], 3, array('intval', 'my_int_val', 'my_int_val'));
		$ppkbb_tcenable_rannounces=my_split_config($config['ppkbb_tcenable_rannounces'], 9, 'my_int_val');
		$type='sticky';
		if($config['board3_ppkbb3cker_portal_exclude_forums_'.$module_id])
		{
			$exclude_forums=my_split_config($config['board3_ppkbb3cker_portal_exclude_forums_'.$module_id], 0, 'my_int_val', ',');
		}

		if($ppkbb_portal_torrents_posttime[0] < 0)
		{
			$type='torrents';
			$ppkbb_portal_torrents_posttime[0]=0;
		}

		$s_display_active=$this->lt_count=0;
		$fetch_announcements = $this->ppkbb_fetch_posts($from_forums, $start, $config['board3_ppkbb3cker_portal_torrents_perpage_'.$module_id], $config['board3_ppkbb3cker_portal_torrents_textlength_'.$module_id], $ppkbb_portal_torrents_posttime, $type, $ppkbb_portal_last_torrents[0], 0, $exclude_forums, $ppkbb_portal_last_torrents, $ppkbb_tcenable_rannounces, $module_id);

		$ppkbb_torrblock_width=my_split_config($config['ppkbb_torrblock_width'], 13, 'my_int_val');
		$ppkbb_portal_lttorrents_display=my_split_config($config['board3_ppkbb3cker_portal_lttorrents_display_'.$module_id], 5, 'my_int_val');
		$ltdisplay_images=$ppkbb_portal_lttorrents_display[1]+$ppkbb_portal_lttorrents_display[2];
		$attachments3=$attachments2=array();
		if(isset($fetch_announcements[0]) && sizeof($fetch_announcements[0]))
		{
			$sql="SELECT * FROM ".ATTACHMENTS_TABLE." WHERE post_msg_id IN('".implode("', '", $fetch_announcements[0])."') AND in_message='0' ORDER BY attach_id DESC";
			$query=$db->sql_query($sql, $ppkbb_portal_last_torrents[3]*60);
			$image_ext=array('gif', 'jpeg', 'jpg', 'png', 'tga', 'tif', 'tiff');
			while($row=$db->sql_fetchrow($query))
			{
				$row['skip_attachment']=0;
				if($row['extension']=='torrent')
				{
					$attachments2[$row['post_msg_id']]['torrents'][]=$row;
					$row['skip_attachment']=1;
				}
				else if(in_array($row['extension'], $image_ext) && $ppkbb_portal_last_torrents[0]!=2)
				{
					if($row['i_poster']==1)
					{
						$attachments2[$row['post_msg_id']]['posters'][]=$row;
					}
					else
					{
						$attachments2[$row['post_msg_id']]['screenshots'][]=$row;
					}
					$row['skip_attachment']=1;
				}
				if(!$ltdisplay_images)
				{
					$attachments2=array();
				}
				$row['i_external'] ? $row['skip_attachment']=1 : '';
				$attachments3[$row['post_msg_id']][]=$row;
			}
			$db->sql_freeresult($query);
		}
		unset($fetch_announcements[0]);
		$ppkbb_tcbonus_upvalue_reset=$ic=0;

		$extensions=$a_ext=$torrents_hashes=array();
		$ppkbb_tcguests_enabled=my_split_config($config['ppkbb_tcguests_enabled'], 2, 'my_int_val');
		$ppkbb_noticedisclaimer_blocks=my_split_config($config['ppkbb_noticedisclaimer_blocks'], 6, 'my_int_val');
		$torrent_top_notice=$torrent_bottom_notice=false;
		if($ppkbb_noticedisclaimer_blocks[5])
		{
			if($user->data['is_registered'] && $ppkbb_noticedisclaimer_blocks[5]!=2)
			{
				$ppkbb_noticedisclaimer_blocks[1] && $user->lang['TORRENT_TOP_NOTICE'] ? $torrent_top_notice=$user->lang['TORRENT_TOP_NOTICE'] : '';
				$ppkbb_noticedisclaimer_blocks[2] && $user->lang['TORRENT_BOTTOM_NOTICE'] ? $torrent_bottom_notice=$user->lang['TORRENT_BOTTOM_NOTICE'] : '';
			}
			else if(!$user->data['is_registered'] && $ppkbb_noticedisclaimer_blocks[5]!=1)
			{
				$ppkbb_noticedisclaimer_blocks[3] && $user->lang['TORRENT_TOP_NOTICE_GUEST'] ? $torrent_top_notice=$user->lang['TORRENT_TOP_NOTICE_GUEST'] : '';
				$ppkbb_noticedisclaimer_blocks[4] && $user->lang['TORRENT_BOTTOM_NOTICE_GUEST'] ? $torrent_bottom_notice=$user->lang['TORRENT_BOTTOM_NOTICE_GUEST'] : '';
			}
		}
		get_lowratio_action();
		for ($i = 1; $i < sizeof($fetch_announcements)+1; $i++)
		{
			$a_fid = (intval($fetch_announcements[$i]['forum_id']));

			if(!$user->data['is_registered'])
			{
				$is_candowntorr = $auth->acl_get('u_candowntorr') && $auth->acl_get('f_candowntorr', $a_fid) && $ppkbb_tcguests_enabled[0] ? 1 : 0;
				$is_candownpostscr = $auth->acl_get('u_candownpostscr') && $auth->acl_get('f_candownpostscr', $a_fid) ? 1 : 0;
			}
			else
			{
				$is_candowntorr=1;
				$is_candownpostscr=1;
				if($user->data['user_id']!=$fetch_announcements[$i]['user_id'])
				{
					$is_candowntorr=$auth->acl_get('u_candowntorr') && $auth->acl_get('f_candowntorr', $a_fid) ? 1 : 0;
					$is_candownpostscr=$auth->acl_get('u_candownpostscr') && $auth->acl_get('f_candownpostscr', $a_fid) ? 1 : 0;
					$user->data['user_lowratio_action'] ? $is_candowntorr=0 : '';
				}
			}
			if((@!$attachments2[$fetch_announcements[$i]['post_id']]['torrents'] && @!$attachments2[$fetch_announcements[$i]['post_id']]['posters'] && @!$attachments2[$fetch_announcements[$i]['post_id']]['screenshots']) || !array_sum($ppkbb_portal_lttorrents_display))
			{
				$ltdisplay=0;
			}
			else
			{
				$ltdisplay=1;
			}
			$message=$attachments='';
			if ($fetch_announcements[$i]['post_attachment'] && $ppkbb_portal_last_torrents[0]==1)
			{
				// Grab extensions
				if(!isset($a_ext[$fetch_announcements[$i]['forum_id']]))
				{
					$extensions = $cache->obtain_attach_extensions($fetch_announcements[$i]['forum_id']);
					$a_ext[$fetch_announcements[$i]['forum_id']]=$extensions;
				}
				else
				{
					$extensions=$a_ext[$fetch_announcements[$i]['forum_id']];
				}
				$message=$fetch_announcements[$i]['post_text'];
				$attachments=@$attachments3[$fetch_announcements[$i]['post_id']];
				parse_attachments($fetch_announcements[$i]['forum_id'], $message, $attachments, $update_count);
			}
			$postrow=array(
				'TITLE'				=> $fetch_announcements[$i]['topic_title'],
				'POSTER'			=> $fetch_announcements[$i]['username'],
				'TIME'				=> $fetch_announcements[$i]['topic_time'],
				'TEXT'				=> $message,
				'REPLIES'			=> $fetch_announcements[$i]['topic_replies'],
				'TOPIC_VIEWS'		=> $fetch_announcements[$i]['topic_views'],
				'U_TOPICS_VIEWS'	=> append_sid($phpbb_root_path . 'viewtopic.' . $phpEx . '?p=' . $fetch_announcements[$i]['post_id']).'#p'.$fetch_announcements[$i]['post_id'],
				'U_VIEW_COMMENTS'	=> append_sid($phpbb_root_path . 'viewtopic.' . $phpEx . '?t=' . $fetch_announcements[$i]['topic_id'] . '&amp;f=' . $a_fid),
				'U_POST_COMMENT'	=> append_sid($phpbb_root_path . 'posting.' . $phpEx . '?mode=reply&amp;t=' . $fetch_announcements[$i]['topic_id'] . '&amp;f=' . $a_fid),
				'S_NOT_LAST'		=> ($i < sizeof($fetch_announcements) - 1) ? true : false,
				'S_HAS_TRACKER_TORRENT' => $ppkbb_portal_lttorrents_display[0] && $is_candowntorr && @$attachments2[$fetch_announcements[$i]['post_id']]['torrents'] ? true : false,
				'S_HAS_TRACKER_POSTER' => $ppkbb_portal_lttorrents_display[1] && $is_candownpostscr && @$attachments2[$fetch_announcements[$i]['post_id']]['posters'] ? true : false,
				'S_HAS_TRACKER_SCREENSHOT' => $ppkbb_portal_lttorrents_display[2] && $is_candownpostscr && @$attachments2[$fetch_announcements[$i]['post_id']]['screenshots'] ? true : false,
				'S_TORRENT_INFO' => $ppkbb_portal_lttorrents_display[3] && $is_candowntorr && @$attachments2[$fetch_announcements[$i]['post_id']]['torrents'] ? true : false,
				'TORRENT_FORUM_LINK'	=> append_sid($phpbb_root_path . 'viewforum.' . $phpEx . '?f=' . $a_fid),
				'TORRENT_FORUM_NAME'	=> $forum_sql[$a_fid]['forum_name'],
				'TORRENT_FORUM_IMAGE' => $forum_sql[$a_fid]['forum_image'] ? '<img src="'.$forum_sql[$a_fid]['forum_image'].'" alt="" title="'.$forum_sql[$a_fid]['forum_name'].'" />' : false,
				'TORRENTS_COUNT' => $i,
				'S_LTDISPLAY_IMAGES' => $ltdisplay_images && $ltdisplay ? true : false,
				'S_LTDISPLAY' => $ltdisplay ? true : false,
				'S_HAS_ATTACHMENTS' => $fetch_announcements[$i]['post_attachment'] && $attachments ? true : false,

				'S_TORRENT_TOP_NOTICE' => $torrent_top_notice,
				'S_TORRENT_BOTTOM_NOTICE' => $torrent_bottom_notice,
			);
			if(/*$ppkbb_portal_lttorrents_display[0] && $is_candowntorr && */@$attachments2[$fetch_announcements[$i]['post_id']]['torrents'])
			{
				/*if($ppkbb_tcenable_rannounces[0] && $ppkbb_tcenable_rannounces[6] && $fetch_announcements[$i]['tr_forb'] < 1 && $ppkbb_portal_last_torrents[0]!=2)
				{
					$torrents_hashes[$row['torrent_id']]=$fetch_announcements[$i]['tr_infohash'];
				}*/
				if(!$config['ppkbb_tcbonus_upvalue'])
				{
					$ppkbb_tcbonus_upvalue_reset=1;
				}
				$config['ppkbb_tcbonus_upvalue']=get_formatted_filesize(!$config['ppkbb_tcbonus_upvalue'] ? $fetch_announcements[$i]['tr_size'] : $config['ppkbb_tcbonus_upvalue'] * 1024 * 1024);
				$tsl_speed=my_split_config($fetch_announcements[$i]['tr_tsl_speed'], 3, 'my_int_val');
				$freetorr_percent=get_freetorr_percent($config['ppkbb_freetorr_percent'], $fetch_announcements[$i]['tr_free']);
				$postrow=array_merge($postrow, array(
					'TORRENT_SIZE' => get_formatted_filesize($fetch_announcements[$i]['tr_size']),
					'TORRENT_FREE' => $fetch_announcements[$i]['tr_free'],
					'TORRENT_FREE_IMG' => $fetch_announcements[$i]['tr_free'] && $freetorr_percent ? '<img src="' . $phpbb_root_path . 'images/tracker/'.$freetorr_percent.'_bookmark_big.png" alt="'. sprintf($user->lang['FREETORR_PERCENT'][$freetorr_percent].' - '.$user->lang['FORM_TORRENT_FREE'], $fetch_announcements[$i]['tr_free'], '%') .'" title="'. sprintf($user->lang['FREETORR_PERCENT'][$freetorr_percent].' - '.$user->lang['FORM_TORRENT_FREE'], $fetch_announcements[$i]['tr_free'], '%') .'"/>' : '',
					'TORRENT_UPLOAD' => $fetch_announcements[$i]['tr_upload'],
					'TORRENT_UPLOAD_IMG' => $fetch_announcements[$i]['tr_upload'] ? '<img src="' . $phpbb_root_path . 'images/tracker/eqchem-big.png" alt="'. sprintf($user->lang['FORM_TORRENT_UP'], $fetch_announcements[$i]['tr_upload'], '%') .'"  title="'. sprintf($user->lang['FORM_TORRENT_UP'], $fetch_announcements[$i]['tr_upload'], '%') .'"/>' : '',
					'TORRENT_BONUS_IMG' => $fetch_announcements[$i]['tr_size'] > $config['ppkbb_tcbonus_fsize'] * 1024 * 1024 && $config['ppkbb_tcbonus_value'] > 0 ? '<img src="' . $phpbb_root_path . 'images/tracker/add_big.png" alt="' . sprintf($user->lang['TORRENT_BONUS'], $config['ppkbb_tcbonus_upvalue'], $config['ppkbb_tcbonus_value']) .'"  title="' . sprintf($user->lang['TORRENT_BONUS'], $config['ppkbb_tcbonus_upvalue'], $config['ppkbb_tcbonus_value']) .'"/>' : '',
					'TORRENT_SEEDERS' => $fetch_announcements[$i]['tr_seeders'],
					'TORRENT_LEECHERS' => $fetch_announcements[$i]['tr_leechers'],
					'TORRENT_REQ_UPLOAD' => $fetch_announcements[$i]['tr_req_upload'],
					'TORRENT_REQ_RATIO' => $fetch_announcements[$i]['tr_req_ratio'],
					'TORRENT_UPSPEED' => get_formatted_filesize($tsl_speed[0], 1, false, 1),
					'TORRENT_DOWNSPEED' => get_formatted_filesize($tsl_speed[1], 1, false, 1),
					'TORRENT_HEALTH' => get_torrent_health($fetch_announcements[$i]['tr_seeders'], $fetch_announcements[$i]['tr_leechers']),
					'TORRENT_COMPLETED' => $fetch_announcements[$i]['tr_completed'],
					)
				);
				$ppkbb_tcbonus_upvalue_reset ? $config['ppkbb_tcbonus_upvalue']=0 : '';
			}
			$template->assign_block_vars('torrents_row', $postrow);
			if ($attachments)
			{
				foreach ($attachments as $attachment)
				{
					$template->assign_block_vars('torrents_row.attachment', array(
						'DISPLAY_ATTACHMENT'	=> $attachment)
					);
				}
			}
			if($ppkbb_portal_lttorrents_display[0]/* && $is_candowntorr*/ && @$attachments2[$fetch_announcements[$i]['post_id']]['torrents'])
			{
				foreach ($attachments2[$fetch_announcements[$i]['post_id']]['torrents'] as $torrent_data)
				{
					$torrent_basename=utf8_basename(urldecode($torrent_data['real_filename']));
					$torrent_shortname=$ppkbb_torrblock_width[2] && utf8_strlen($torrent_basename) > $ppkbb_torrblock_width[2] ? utf8_substr($torrent_basename, 0, $ppkbb_torrblock_width[2]).'...' : $torrent_basename;
					$template->assign_block_vars('torrents_row.torrent_fields', array(
						'TORRENT_LINK' => $is_candowntorr ? append_sid("{$phpbb_root_path}download/file.$phpEx", 'id=' . (int) $torrent_data['attach_id'], true, ($torrent_data['is_orphan']) ? $user->session_id : false) : false,
						'TORRENT_DOWNLOAD_IMG' => $phpbb_root_path . 'images/tracker/filesave_big.png',
						'TORRENT_DOWNLOAD_SMALLIMG' => $phpbb_root_path . 'images/tracker/filesave.png',
						'TORRENT_DOWNLOAD_NAME'		=> $torrent_basename,
						'TORRENT_ALTITLE'			=> $torrent_basename,
						)
					);
				}
			}
			if($ppkbb_portal_lttorrents_display[1] && $is_candownpostscr && @$attachments2[$fetch_announcements[$i]['post_id']]['posters'] && $ppkbb_portal_last_torrents[0]!=2)
			{
				$ic+=1;
				foreach ($attachments2[$fetch_announcements[$i]['post_id']]['posters'] as $poster_data)
				{

					if(!$poster_data['i_external'])
					{
						$poster_addon='';
						if($poster_data['thumbnail'] && $ppkbb_portal_lttorrents_display[1]==1)
						{
							$poster_addon='&amp;t=1';
						}
						$poster_basename=utf8_basename($poster_data['real_filename']);

							$poster_wh=tracker_get_thumb_size($poster_data['i_width'], $poster_data['i_height'], $ppkbb_torrblock_width[4], $ppkbb_torrblock_width[5], ($ppkbb_torrblock_width[12] ? true : false));

						$template->assign_block_vars('torrents_row.torrent_poster_fields', array(
							'POSTER_LINK' => append_sid("{$phpbb_root_path}download/file.$phpEx", 'id=' . (int) $poster_data['attach_id'], true, ($poster_data['is_orphan']) ? $user->session_id : false).'&amp;ext=.'.$poster_data['extension'],
							'POSTER_SRC' =>append_sid("{$phpbb_root_path}download/file.$phpEx", 'id=' . $poster_data['attach_id'] . $poster_addon),
							'POSTER_WH_WIDTH' => $poster_wh[0] ? $poster_wh[0] : false,
							'POSTER_WH_HEIGHT' => $poster_wh[1] ? $poster_wh[1] : false,
							'POSTER_COUNT' => $ic,
							'POSTER_FORUM' => 1,
							)
						);
					}
					else
					{

							$poster_wh=tracker_get_thumb_size($poster_data['i_width'], $poster_data['i_height'], $ppkbb_torrblock_width[4], $ppkbb_torrblock_width[5], ($ppkbb_torrblock_width[12] ? true : false));

						$template->assign_block_vars('torrents_row.torrent_poster_fields', array(
							'POSTER_LINK'=>$poster_data['real_filename'],
							'POSTER_SRC' => $poster_data['real_filename'],
							'POSTER_WH_WIDTH' => $poster_wh[0] ? $poster_wh[0] : false,
							'POSTER_WH_HEIGHT' => $poster_wh[1] ? $poster_wh[1] : false,
							'POSTER_COUNT'=>$ic,
							'POSTER_FORUM'=>0,
							)
						);
					}

				}
			}
			if($ppkbb_portal_lttorrents_display[2] && $is_candownpostscr && @$attachments2[$fetch_announcements[$i]['post_id']]['screenshots'] && $ppkbb_portal_last_torrents[0]!=2)
			{
				$ic+=1;
				foreach ($attachments2[$fetch_announcements[$i]['post_id']]['screenshots'] as $screenshot_data)
				{
					if(!$screenshot_data['i_external'])
					{
						$screenshot_addon='';
						if($screenshot_data['thumbnail'] && $ppkbb_portal_lttorrents_display[2]==1)
						{
							$screenshot_addon='&amp;t=1';
						}
						$screenshot_basename=utf8_basename($screenshot_data['real_filename']);
						$screenshot_wh=tracker_get_thumb_size($screenshot_data['i_width'], $screenshot_data['i_height'], $ppkbb_torrblock_width[6], $ppkbb_torrblock_width[7], ($ppkbb_torrblock_width[12] ? true : false));
						$template->assign_block_vars('torrents_row.torrent_screenshot_fields', array(
							'SCREENSHOT_LINK' => append_sid("{$phpbb_root_path}download/file.$phpEx", 'id=' . (int) $screenshot_data['attach_id'], true, ($screenshot_data['is_orphan']) ? $user->session_id : false).'&amp;ext=.'.$screenshot_data['extension'],
							'SCREENSHOT_SRC' => append_sid("{$phpbb_root_path}download/file.$phpEx", 'id=' . $screenshot_data['attach_id'] . $screenshot_addon),
							'SCREENSHOT_WH_WIDTH' => $screenshot_wh[0] ? $screenshot_wh[0] : false,
							'SCREENSHOT_WH_HEIGHT' => $screenshot_wh[1] ? $screenshot_wh[1] : false,
							'SCREENSHOT_COUNT' => $ic,
							'SCREENSHOT_FORUM' => 1,
							)
						);
					}
					else
					{
						$screenshot_wh=tracker_get_thumb_size($screenshot_data['i_width'], $screenshot_data['i_height'], $ppkbb_torrblock_width[6], $ppkbb_torrblock_width[7], ($ppkbb_torrblock_width[12] ? true : false));
						$template->assign_block_vars('torrents_row.torrent_screenshot_fields', array(
							'SCREENSHOT_LINK' => $screenshot_data['real_filename'],
							'SCREENSHOT_SRC' => $screenshot_data['real_filename'],
							'SCREENSHOT_WH_WIDTH' => $screenshot_wh[0] ? $screenshot_wh[0] : false,
							'SCREENSHOT_WH_HEIGHT' => $screenshot_wh[1] ? $screenshot_wh[1] : false,
							'SCREENSHOT_COUNT' => $ic,
							'SCREENSHOT_FORUM' => 0,
							)
						);
					}
				}
			}
		}

		$template->assign_vars(array(
			'TORR_TABLE_WIDTH' => intval($config['ppkbb_tmax_thumbwidth']+$ppkbb_torrblock_width[0]),
			'IMG_THUMB_WIDTH' => $config['ppkbb_tmax_thumbwidth'],
			'TP_PAGINATION'	=> generate_portal_pagination(append_sid("{$phpbb_root_path}portal.{$phpEx}", "mode=portal"), $this->lt_count, $config['board3_ppkbb3cker_portal_torrents_perpage_'.$module_id], $start, 'torrents'),
			'TP_PAGE_NUMBER'	=> on_page($this->lt_count, $config['board3_ppkbb3cker_portal_torrents_perpage_'.$module_id], $start),
			'TP_TOTAL_TORRENTS' => ($this->lt_count == 1) ? $user->lang['VIEW_LATEST_TORRENT'] : sprintf($user->lang['VIEW_LATEST_TORRENTS'], $this->lt_count),
			'LATEST_TORR_COUNT' => $this->lt_count ? 1 : 0,
			'S_AS_MESSAGES' => $ppkbb_portal_last_torrents[0]==1 ? true : false,

			'POSTERS_HEIGHT' => $ppkbb_portal_last_torrents[2] ? $ppkbb_portal_last_torrents[2] : 200,
			)
		);

		if($show_module)
		{
			return 'ppkbb3cker_ltorrents_center.html';
		}
	}

	public function get_template_acp($module_id)
	{
		return array(
			'title'	=> 'PPKBB3CKER_LTORRENTS',
			'vars'	=> array(
				'legend1'									=> 'ACP_PPKBB3CKER_LTORRENTS_SETTINGS',
				'board3_ppkbb3cker_portal_last_torrents_'.$module_id		=> array('lang' => 'DISPLAY_LATESTTORRENTS', 'validate' => 'string',   	'type' => 'text:15:15',  'explain' => true),
				'board3_ppkbb3cker_portal_torrents_perpage_'.$module_id		=> array('lang' => 'PORTAL_TORR_PERPAGE', 'validate' => 'int:0',   	'type' => 'text:3:3',  'explain' => true),
				'board3_ppkbb3cker_portal_torrents_textlength_'.$module_id		=> array('lang' => 'PORTAL_TORR_TEXTLENGTH', 'validate' => 'int:0',   	'type' => 'text:5:5',  'explain' => true),
				'board3_ppkbb3cker_portal_torrents_posttime_'.$module_id		=> array('lang' => 'PORTAL_TORR_TIME', 'validate' => 'string',   	'type' => 'text:10:10',  'explain' => true),
				'board3_ppkbb3cker_portal_exclude_forums_'.$module_id			=> array('lang' => 'PORTAL_EXCLUDE_FORUMS',	'validate' => 'string', 'type' => 'custom', 'explain' => true, 'method' => 'select_tracker_forums2', 'submit' => 'store_selected_tracker_forums2'),
				'board3_ppkbb3cker_portal_trueexclude_forums_'.$module_id		=> array('lang' => 'PORTAL_TRUEEXCLUDE_FORUMS', 'validate' => 'int',   	'type' => 'radio:yes_no',  'explain' => true),
				'board3_ppkbb3cker_portal_lttorrents_display_'.$module_id		=> array('lang' => 'PORTAL_LTDISPLAY_OPT', 'validate' => 'string',   	'type' => 'text:7:7',  'explain' => true),
			),
		);
	}

	public function select_tracker_forums2($value, $key)
	{
		global $user, $config;

		$forum_list = make_forum_select(false, false, true, false, true, false, true, 1);

		$selected = array();
		if(isset($config[$key]) && strlen($config[$key]) > 0)
		{
			$selected = explode(',', $config[$key]);
		}
		// Build forum options
		$s_forum_options = '<select id="' . $key . '" name="' . $key . '[]" multiple="multiple">';
		foreach ($forum_list as $f_id => $f_row)
		{
			$s_forum_options .= '<option value="' . $f_id . '"' . ((in_array($f_id, $selected)) ? ' selected="selected"' : '') . (($f_row['disabled']) ? ' disabled="disabled" class="disabled-option"' : '') . '>' . $f_row['padding'] . $f_row['forum_name'] . '</option>';
		}
		$s_forum_options .= '</select>';

		return $s_forum_options;
	}

	public function store_selected_tracker_forums2($key, $module_id)
	{
		global $db, $cache;

		// Get selected forums
		$values = request_var($key, array(0 => ''));

		$forums = implode(',', $values);

		set_tracker_config($key, $forums);

	}

	public function ppkbb_fetch_posts($from_forums, $start, $number_of_posts, $text_length, $ppkbb_portal_torrents_posttime, $type, $mode=1, $ltorrents_catfilter, $exclude_forums, $ppkbb_portal_last_torrents, $ppkbb_tcenable_rannounces, $module_id)
	{
		global $db, $phpbb_root_path, $phpEx, $auth, $user, $config;

		$from_forum=($from_forums) ? ($ppkbb_portal_torrents_posttime[1] ? 'tr' : 't').".forum_id IN ('" . $from_forums . "') AND " : '';
		$from_forum.=$exclude_forums ? ($ppkbb_portal_torrents_posttime[1] ? 'tr' : 't').".forum_id ".($config['board3_ppkbb3cker_portal_trueexclude_forums_'.$module_id] ? 'NOT '  : '')."IN('".implode("', '", $exclude_forums)."') AND " : '';
		$post_time = ($ppkbb_portal_torrents_posttime[0] == 0) ? '' : ($ppkbb_portal_torrents_posttime[1] ? 'tr.added > ' : 't.topic_time > ') . (time() - $ppkbb_portal_torrents_posttime[0] * 86400) . ' AND';

		if ($type == 'announcements')
		{
			// only global announcements for announcements block
			$topic_type = '( t.topic_type = ' . POST_ANNOUNCE . ') AND';
		}
		else if ($type == 'sticky')
		{
			// only sticky topics/posts for torrents block
			$topic_type = '( t.topic_type = ' . POST_STICKY . ' ) AND';
		}
		else if ($type == 'news_all')
		{
			// not show global announcements
			$topic_type = '( t.topic_type != ' . POST_ANNOUNCE . ' ) AND';
		}
		else if ($type == 'torrents')
		{
			// not show global announcements
			$topic_type = '( t.topic_type != ' . POST_GLOBAL . ' ) AND';
		}
		else
		{
			// only normal topic
			$topic_type = 't.topic_type = ' . POST_NORMAL . ' AND';
		}

		$sql = 'SELECT
				COUNT(*) lt_count
			FROM
				' . TOPICS_TABLE . ' AS t,
				' . USERS_TABLE . ' AS u,
				' . TRACKER_TORRENTS_TABLE . ' AS tr,
				' . POSTS_TABLE . ' AS p
			WHERE
				' . $topic_type . '
				' . $from_forum . '
				' . $post_time . "
				t.topic_poster = u.user_id AND
				t.topic_first_post_id = p.post_id AND
				t.topic_status != 2 AND
				t.topic_approved = 1 AND
				tr.topic_id = p.topic_id AND
				tr.forb < 1
				".($ppkbb_portal_torrents_posttime[2] ? ' AND tr.seeders'.($ppkbb_tcenable_rannounces[0] ? '+tr.rem_seeders' : '').' > '.($ppkbb_portal_torrents_posttime[2]-1) : '');
		$result = $db->sql_query($sql, $ppkbb_portal_last_torrents[3]*60);
		$this->lt_count = (int) $db->sql_fetchfield('lt_count');
		$db->sql_freeresult($result);

		$posts = array();

		if(!$this->lt_count)
		{
			return $posts;
		}

		$sql = 'SELECT
				t.forum_id,
				t.topic_id,
				t.topic_last_post_id,
				t.topic_time,
				t.topic_title,
				t.topic_attachment,
				t.topic_views,
				t.topic_replies,
				t.forum_id,
				t.topic_poster,
				u.username,
				u.user_id,
				u.user_type,
				u.user_colour,
				tr.id torrent_id,
				tr.size,
				tr.free,
				tr.upload,
				tr.seeders'.($ppkbb_tcenable_rannounces[0] ? '+tr.rem_seeders' : '').' seeders,
				tr.leechers'.($ppkbb_tcenable_rannounces[0] ? '+tr.rem_leechers' : '').' leechers,
				tr.req_upload,
				tr.req_ratio,
				tr.tsl_speed,
				tr.times_completed'.($ppkbb_tcenable_rannounces[0] ? '+tr.rem_times_completed' : '').' times_completed,
				tr.info_hash,
				tr.forb,
				p.post_id,
				p.post_text,
				p.post_attachment,
				p.enable_smilies,
				p.enable_bbcode,
				p.enable_magic_url,
				p.bbcode_bitfield,
				p.bbcode_uid
			FROM
				' . TOPICS_TABLE . ' AS t,
				' . USERS_TABLE . ' AS u,
				' . TRACKER_TORRENTS_TABLE . ' AS tr,
				' . POSTS_TABLE . ' AS p
			WHERE
				' . $topic_type . '
				' . $from_forum . '
				' . $post_time . "
				t.topic_poster = u.user_id AND
				t.topic_first_post_id = p.post_id AND
				t.topic_status != 2 AND
				t.topic_approved = 1 AND
				tr.topic_id = p.topic_id AND
				tr.forb < 1
				".($ppkbb_portal_torrents_posttime[2] ? ' AND tr.seeders'.($ppkbb_tcenable_rannounces[0] ? '+tr.rem_seeders' : '').' > '.($ppkbb_portal_torrents_posttime[2]-1) : '')."
			ORDER BY
				".($ppkbb_portal_torrents_posttime[1] ? 'tr.id' : 't.topic_id')." DESC LIMIT {$start}, {$number_of_posts}";

		// query the database
		$result = $db->sql_query($sql, $ppkbb_portal_last_torrents[3]*60);

		if($mode==1)
		{
			include_once($phpbb_root_path . 'includes/bbcode.' . $phpEx);
			$bbcode = new bbcode();
		}

		$i = 1;
		while ( ($row = $db->sql_fetchrow($result)) && ( ($i-1 < $number_of_posts) || ($number_of_posts == '0') ) )
		{
			//if ( ($auth->acl_get('f_read', $row['forum_id'])) || ($row['forum_id'] == '0') )
			//{
				if($mode==1)
				{
					$message = $row['post_text'];

					// Parse the message and subject
					$message = censor_text($message);

					// Second parse bbcode here
					if ($row['bbcode_bitfield'])
					{
						$bbcode->bbcode_second_pass($message, $row['bbcode_uid'], $row['bbcode_bitfield']);
					}
					$message = bbcode_nl2br($message);
					$message = smiley_text($message);

					if (($text_length != 0) && (strlen($message) > $text_length))
					{
						$message = $this->closetags(substr($message, 0, $text_length));
						$message .= '...';
					}

					$row['post_text']= $message;
				}
				$row['topic_title'] = censor_text($row['topic_title']);

				$row['post_attachment'] ? $posts[0][]=$row['post_id'] : '';
				$posts[$i]['post_text'] = $mode==1 ? $row['post_text'] : '';
				$posts[$i]['topic_id'] = $row['topic_id'];
				$posts[$i]['topic_last_post_id'] = $row['topic_last_post_id'];
				$posts[$i]['forum_id'] = $row['forum_id'];
				$posts[$i]['topic_replies'] = $row['topic_replies'];
				$posts[$i]['topic_time'] = $user->format_date($row['topic_time']);
				$posts[$i]['topic_title'] = $row['topic_title'];
				$posts[$i]['post_id'] = $row['post_id'];
				$posts[$i]['username'] =  get_username_string('full', $row['user_id'], $row['username'], $row['user_colour']);
				$posts[$i]['user_id'] = $row['user_id'];
				$posts[$i]['user_type'] = $row['user_type'];
				$posts[$i]['user_user_colour'] = $row['user_colour'];
				$posts[$i]['post_attachment'] = ($row['post_attachment']) ? true : false;
				$posts[$i]['topic_views'] = $row['topic_views'];
				$posts[$i]['tr_tid'] = $row['torrent_id'];
				$posts[$i]['tr_size'] = $row['size'];
				$posts[$i]['tr_free'] = $row['free'];
				$posts[$i]['tr_upload'] = $row['upload'];
				$posts[$i]['tr_seeders'] = $row['seeders'];
				$posts[$i]['tr_leechers'] = $row['leechers'];
				$posts[$i]['tr_req_upload'] = $row['req_upload'];
				$posts[$i]['tr_req_ratio'] = $row['req_ratio'];
				$posts[$i]['tr_tsl_speed'] = $row['tsl_speed'];
				$posts[$i]['tr_completed'] = $row['times_completed'];
				$posts[$i]['tr_infohash'] = $row['info_hash'];
				$posts[$i]['tr_forb'] = $row['forb'];
				$i++;
			//}
		}
		$db->sql_freeresult($result);
		// return the result
		return $posts;
	}

	public function closetags($text, $ex=array('area', 'base', 'basefont', 'br', 'col', 'frame', 'hr', 'img', 'input', 'isindex', 'link', 'meta', 'param'))
	{
		$text = substr($text, 0, strrpos($text," "));
		$text = preg_replace("/<[^>]*$/i", "", $text);
		preg_match_all("/<[^a-z>\/]*([a-z]{1,50})/i", $text, $otags);
		if(count($otags[0])>0)
		{
			$fotags=$fctags=array();
			preg_match_all("/<[ t]*\/[^a-z]*([a-z]{1,50})/i", $text, $ctags);
			foreach($otags[1] as $otag)
			{
				$otag = strtolower($otag);
				if(isset($fotags[$otag]))
				{
					$fotags[$otag]++;
				}
				else
				{
					$fotags[$otag] = 1;
				}
			}
			foreach($ctags[1] as $ctag)
			{
				$ctag = strtolower($ctag);
				if(isset($fctags[$ctag]))
				{
					$fctags[$ctag]++;
				}
				else
				{
					$fctags[$ctag] = 1;
				}
			}
			while(list($tag, $cnt) = each($fotags))
			{
				if(in_array($tag, $ex))
				{
					continue;
				}
				$fctags[$tag] = isset($fctags[$tag]) ? $fctags[$tag] : 0;
				$text.=str_repeat("</$tag>", abs($fctags[$tag] - $cnt));
			}
		}
		return $text;
	}

	/**
	* API functions
	*/
	public function install($module_id)
	{
		set_config('board3_ppk_ltorrents_number_' . $module_id, 1);
		set_tracker_config('board3_ppkbb3cker_portal_last_torrents_'.$module_id, '1 0 0 1');
		set_tracker_config('board3_ppkbb3cker_portal_torrents_perpage_'.$module_id, '10');
		set_tracker_config('board3_ppkbb3cker_portal_torrents_textlength_'.$module_id, '300');
		set_tracker_config('board3_ppkbb3cker_portal_torrents_posttime_'.$module_id, '-1 1 0');
		set_tracker_config('board3_ppkbb3cker_portal_exclude_forums_'.$module_id, '');
		set_tracker_config('board3_ppkbb3cker_portal_trueexclude_forums_'.$module_id, 1);
		set_tracker_config('board3_ppkbb3cker_portal_lttorrents_display_'.$module_id, '1 2 3 4');
		purge_tracker_config(true);
		return true;
	}

	public function uninstall($module_id)
	{
		global $db;

		$del_config = array(
			'board3_ppk_ltorrents_number_' . $module_id,
			'board3_ppkbb3cker_portal_last_torrents_'.$module_id,
			'board3_ppkbb3cker_portal_torrents_perpage_'.$module_id,
			'board3_ppkbb3cker_portal_torrents_textlength_'.$module_id,
			'board3_ppkbb3cker_portal_torrents_posttime_'.$module_id,
			'board3_ppkbb3cker_portal_exclude_forums_'.$module_id,
			'board3_ppkbb3cker_portal_trueexclude_forums_'.$module_id,
			'board3_ppkbb3cker_portal_lttorrents_display_'.$module_id,
		);
		$sql = 'DELETE FROM ' . TRACKER_CONFIG_TABLE . '
			WHERE ' . $db->sql_in_set('config_name', $del_config);
		$db->sql_query($sql);
		purge_tracker_config(true);
		$sql = 'DELETE FROM ' . CONFIG_TABLE . '
			WHERE ' . $db->sql_in_set('config_name', $del_config);
		return $db->sql_query($sql);
	}
}
